package com.ljy.tkuser.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljy.tkuser.entity.LjyBigUser;
import com.ljy.tkuser.entity.reqvo.ReqVOLjyBigUser;
import com.ljy.tkuser.mapper.LjyBigUserMapper;
import com.ljy.tkuser.service.LjyBigUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljy.tkuser.util.JwtUtils;
import com.ljy.tkuser.util.State;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户登录表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-12-27
 */
@Service
public class LjyBigUserServiceImpl extends ServiceImpl<LjyBigUserMapper, LjyBigUser> implements LjyBigUserService {

    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public HashMap pageUserConditionSelect(ReqVOLjyBigUser reqVOLjyBigUser) {
        //分页判断
        Long current = 0L, limit = 0L;
        if (StringUtils.isEmpty(reqVOLjyBigUser.getCurrentPage())) {
            current = 1L;
        } else {
            current = reqVOLjyBigUser.getCurrentPage();
        }

        if (StringUtils.isEmpty(reqVOLjyBigUser.getLimitSize())) {
            limit = 20L;
        } else {
            limit = reqVOLjyBigUser.getLimitSize();
        }

//        if (StringUtils.isEmpty(reqVOLjyBigUser.getStatus())){
//            reqVOLjyBigUser.setStatus(true);
//        }
        Page<LjyBigUser> page = new Page<>(current, limit);
        QueryWrapper<LjyBigUser> wrapper = new QueryWrapper<>();
        //sql 返回数据包装
        wrapper.select("user_id", "westernmd_1011_userid", "status", "last_time", "colleges_id", "colleges_name",
                "major_id", "major_name", "postgraduate_id", "postgraduate_name", "postgraduate_major_id", "postgraduate_major_name",
                "hospital");
        //筛选条件判断
        //前端条件数据
        String nickName = reqVOLjyBigUser.getNickname();
        Boolean status = reqVOLjyBigUser.getStatus();
        //本科院校id
        Integer collegesId = reqVOLjyBigUser.getCollegesId();
        //本科专业id
        Integer majorId = reqVOLjyBigUser.getMajorId();
        //考研院校专业id
        Integer postgraduateMajorId = reqVOLjyBigUser.getPostgraduateMajorId();
        //考研院校
        Integer postgraduateId = reqVOLjyBigUser.getPostgraduateId();
        //医院
        String hospital = reqVOLjyBigUser.getHospital();
        //时间
        Date createdAt = reqVOLjyBigUser.getCreatedAt();
        if (!StringUtils.isEmpty(nickName)) {
            //模糊查询昵称
            wrapper.like("nickname", nickName);
        }
        if (status.equals(false) || status.equals("0")) {
            wrapper.eq("status", 0);
        }
        //本科院校id
        if (!StringUtils.isEmpty(collegesId) && collegesId != 0) {
            wrapper.eq("colleges_id", collegesId);
        }
        //本科专业id
        if (!StringUtils.isEmpty(majorId) && majorId != 0) {
            wrapper.eq("major_id", majorId);
        }
        //考研院校
        if (!StringUtils.isEmpty(postgraduateId) && postgraduateId != 0) {
            wrapper.eq("postgraduate_id", postgraduateId);
        }
        //考研院校专业id
        if (!StringUtils.isEmpty(postgraduateMajorId) && postgraduateMajorId != 0) {
            wrapper.eq("postgraduate_major_id", postgraduateMajorId);
        }
        //医院
        if (!StringUtils.isEmpty(hospital)) {
            wrapper.eq("hospital", hospital);
        }
        //创建时间 2021-03-01
        if (!StringUtils.isEmpty(createdAt)) {
            wrapper.gt("created_at", createdAt);
        }
        //组合条件查询数据
        //this.page(page,wrapper);
        IPage<LjyBigUser> iPage = this.baseMapper.selectPage(page, wrapper);
        long total = iPage.getTotal();
        List<LjyBigUser> records = iPage.getRecords();

        //组合返回数据
        HashMap map = new HashMap();
        map.put("current", current);
        map.put("limit", limit);
        map.put("total", total);
        map.put("records", records);
        return map;
    }

    @Override
    public int insertUserInfo(ReqVOLjyBigUser reqVOLjyBigUser) {
        LjyBigUser ljyBigUser = new LjyBigUser();
        BeanUtils.copyProperties(reqVOLjyBigUser, ljyBigUser);
        return baseMapper.insert(ljyBigUser);
    }

    @Override
    public int PutUserInfo(LjyBigUser ljyBigUser) {
        return baseMapper.updateById(ljyBigUser);
    }

    @Override
    public HashMap<String, Object> UserConditionSelect(String nikeName, String passWord,HttpServletResponse response) throws UnsupportedEncodingException {
        HashMap<String, Object> userMap = new HashMap<>();
        if (StringUtils.isEmpty(nikeName)) {
            userMap.put(State.KEY_CODE, State.CODE_ERROR);
            userMap.put(State.KEY_MESSAGE, State.USER_ERROR_MESSAGE);
            userMap.put(State.KEY_DATA, "null");
            return userMap;
        }
        if (StringUtils.isEmpty(passWord)) {
            userMap.put(State.KEY_CODE, State.CODE_ERROR);
            userMap.put(State.KEY_MESSAGE, State.PASS_ERROR_MESSAGE);
            userMap.put(State.KEY_DATA, "null");
            return userMap;
        }
        QueryWrapper<LjyBigUser> wrapper = new QueryWrapper<>();
        wrapper.eq("nickname", nikeName);
        wrapper.eq("password", passWord);
        LjyBigUser ljyBigUser = baseMapper.selectOne(wrapper);
        //查询到数据返回  没有查询到 说明没有这个用户
        if(!StringUtils.isEmpty(ljyBigUser)){
//            session.setAttribute("loginUser"+":"+ljyBigUser.getUserId(),ljyBigUser);
//            String jwtToken = JwtUtils.getJwtToken(ljyBigUser.getUserId().toString(), ljyBigUser.getNickname());
//            response.setHeader("token",jwtToken);
            String userInfo = JSON.toJSONString(ljyBigUser);
            //java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value
            //cookie 里面有单引号报的错误
            String encode = URLEncoder.encode(userInfo, "utf-8");

            redisTemplate.opsForValue().set("userCookie",encode);

            //todo cookie加密
            Cookie cookie = new Cookie("userInfo",encode);
            cookie.setPath("/");
            response.addCookie(cookie);
//            session.setAttribute("userName:"+nikeName,ljyBigUser);
//            session.setAttribute("loginUser",ljyBigUser);
            userMap.put(State.KEY_CODE, State.CODE_SUCCESS);
            userMap.put(State.KEY_MESSAGE, State.SUCCESS_MESSAGE);
            userMap.put(State.KEY_DATA, ljyBigUser);
        }else {
            userMap.put(State.KEY_CODE, State.CODE_SUCCESS);
            userMap.put(State.KEY_MESSAGE, State.USER_NUll_MESSAGE);
            userMap.put(State.KEY_DATA, null);
        }
        //TODO 可返回铭文userMap，可返回密文jwtToken
        return userMap;
    }

    @Override
    public LjyBigUser getUser( HttpServletRequest request) throws UnsupportedEncodingException {
//        String userID = JwtUtils.getMemberIdByJwtToken(request);
//        LjyBigUser user = baseMapper.selectById(userID);
        Cookie[] cookies = request.getCookies();
        String userInfo = cookies[0].getValue();
        String decode = URLDecoder.decode(userInfo, "utf-8");
        JSONObject jsonObject = JSONObject.parseObject(decode);
        LjyBigUser ljyBigUser = JSON.toJavaObject(jsonObject, LjyBigUser.class);

        redisTemplate.opsForValue().set("userCookie",ljyBigUser);
        return ljyBigUser;
    }

    @Override
    public void loutUser(HttpSession session) {
        session.removeAttribute("loginUser");
    }
}
